/* Copyright (c) 2010 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.orkut.client.api.samples.greetings.server;

import com.google.appengine.repackaged.com.google.common.util.Base64;
import com.google.inject.Inject;
import com.google.orkut.client.api.samples.greetings.shared.CommonConstants;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Creates and verifies post-tokens.
 *
 * @author Shishir Birmiwal
 */
public class PostTokenServices {
  private final CachedConfig config;

  @Inject
  public PostTokenServices(CachedConfig config) {
    this.config = config;
  }

  public String createPostToken(String cookie) {
    MessageDigest digest;
    try {
      digest = MessageDigest.getInstance("SHA-1");
      digest.reset();
      String encString = cookie + config.getConfig().getPostTokenSalt();
      byte[] input = digest.digest(encString.getBytes("UTF-8"));
      return Base64.encode(input);
    } catch (NoSuchAlgorithmException e) {
      // should not happen
    } catch (UnsupportedEncodingException e) {
      // should not happen
    }
    // return the cookie itself as the post token if we have these exceptions
    // this should never happen, really
    return cookie;
  }

  public String createPostToken(HttpServletRequest req) {
    Cookie[] cookies = req.getCookies();
    if (cookies == null) {
      return null;
    }
    for (Cookie cookie : cookies) {
      if (cookie.getName().equals(CommonConstants.COOKIE)) {
        return createPostToken(cookie.getValue());
      }
    }
    return null;
  }

  public boolean verifyRequest(String cookie, String postToken) {
    return createPostToken(cookie).equals(postToken);
  }

  public boolean verifyRequest(HttpServletRequest req, String postToken) {
    Cookie[] cookies = req.getCookies();
    for (Cookie cookie : cookies) {
      if (cookie.getName().equals(CommonConstants.COOKIE)) {
        return verifyRequest(cookie.getValue(), postToken);
      }
    }
    return false;
  }
}
